/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.passwords;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Comparator;
import org.json.JSONObject;
import org.webos.java.base.Frame;
import org.webos.java.base.FrameType;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.SystemManager;
import org.webos.java.base.grid.GridController;
import org.webos.java.base.grid.GridControllerItem;
import org.webos.java.base.utils.CryptoUtil;
import org.webos.java.base.workspace.Workspace;
import org.webos.java.root.Log;


class PasswordItem extends GridControllerItem {

    int id;
    String name;
    String login;
    String password;
    String url;
    String notes;

    public PasswordItem(GridController aController, int aID, String aName, 
            String aLogin, String aPassword, String aURL, String aNotes) {
        super(aController, null, Integer.toString(aID));
        id = aID;
        name = aName;
        login = aLogin;
        password = aPassword;
        url = aURL;
        notes = aNotes;
    }

    public void objectTOJSON(JSONObject aObject) {
        String lName = name.toLowerCase();
        String link = null;
        String caption = name;
        if(!url.equals("")){
            link = url;
            if("".equals(name))
                caption = url;
        }else{
            if(lName.startsWith("http://") || lName.startsWith("https://")){
                link = lName;
            }
            if(lName.startsWith("www") && lName.indexOf(" ")==-1){
                link = lName;
            }
        }
        if(link!=null){
            if(!link.startsWith("http://") && !link.startsWith("https://")){
                link = "http://"+link;
            }
            if(caption.length()>30){
                caption = caption.substring(0, 29)+"...";
            }
            aObject.putOpt("name", "<a href=\""+link+"\" target=\"_blank\" class=\"passwords_link\">"+caption+"</a>");
        }else
            aObject.putOpt("name", SystemManager.prepareTextForView(name, true));
    }
}
/**
 *
 * @author kostya
 */
@FrameType(code="table", jsClass="passwords.Grid")
public class PasswordsFrame extends Frame<PasswordManager>{

    GridController<PasswordItem> controller = new GridController<PasswordItem>(this);
    CategorieItem categorieItem = null;

    public PasswordsFrame(PasswordManager aManager, Workspace aWorkspace) {
        super(aManager, aWorkspace);
        setIcon("passwords_icns passwords_icn_passwords");
        setShowStatus(true);
        passwordStateChanged(false);
        controller.setComparator(new Comparator<PasswordItem>() {

            public int compare(PasswordItem o1, PasswordItem o2) {
                return o1.name.compareToIgnoreCase(o2.name);
            }
        });
    }

    void displayPasswords(CategorieItem aItem){
        controller.setSilent(true);
        controller.clear();
        categorieItem = aItem;
        if(aItem!=null){
            setTitle(aItem.name+" passwords");
            try {
                PreparedStatement st = getApplication().connection.prepareQuery(
                        "select id, name, username, " +
                        "password, url, notes, create_date from PASSWORDS where id_cat=?");
                st.setInt(1, aItem.id);
                ResultSet rset = st.executeQuery();
                while(rset.next()){
//                    Log.debug(this, "Adding new item to grid", rset.getString(2));
                    controller.appendItem(new PasswordItem(controller, rset.getInt(1),
                            rset.getString(2), rset.getString(3), rset.getString(4),
                            rset.getString(5), rset.getString(6)));
                }
            } catch (Throwable t) {
                Log.error(this, "Exception thrown: " + t.getMessage());
                t.printStackTrace();
            }
        }else{
            setTitle("No folder selected!");
        }
        controller.sendGrid();
        
    }

    @RemoteMessage
    public void editPassword(JSONObject aObject){
        PasswordItem item = controller.getItem(aObject.optString("id", ""));
        if(item!=null)
            new EntryEditor(getApplication(), item);
    }

    @RemoteMessage
    public JSONObject showPassword(JSONObject aData){
        try {
            PasswordItem item = controller.getItem(aData.optString("id", ""));
            if(item!=null){
                String masterPassword = getApplication().getPassword();
                if(masterPassword==null){
                    return null;
                }
                JSONObject result = new JSONObject();
                result.putOpt("login", CryptoUtil.decode(masterPassword, item.login));
                result.putOpt("password", CryptoUtil.decode(masterPassword, item.password));
                return result;
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @RemoteMessage
    public JSONObject showPasswordMobile(JSONObject aData){
        try {
            PasswordItem item = controller.getItem(aData.optString("id", ""));
            if(item!=null){
                new MobileView(getApplication(), item);
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @RemoteMessage
    public void lockPassword(JSONObject aObject){
        getApplication().lockPassword();
    }

    @RemoteMessage
    public JSONObject newPassword(JSONObject aObject){
        try {
            if(categorieItem!=null){
                new EntryEditor(getApplication(), null);
                return null;
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return NetworkManager.getErrorObject(1004, "Can't create password, no folder selected");
    }

    void passwordStateChanged(boolean aEntered){
        setStatus(aEntered? "Passwords are unlocked": "Passwords are locked");
    }

    @RemoteMessage
    public void showSettings(JSONObject aObject){
        new SettingsWindow(getApplication());
    }

}
